package cn.com.darly.videoandroidpm.ui.service;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;

import com.darly.common.DLog;
import com.darly.common.ToastApp;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.eclipse.paho.android.service.MqttAndroidClient;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.List;
import java.util.Random;

import cn.com.darly.videoandroidpm.R;
import cn.com.darly.videoandroidpm.base.BaseApplication;
import cn.com.darly.videoandroidpm.bean.LoginInfo;
import cn.com.darly.videoandroidpm.bean.MessageInfo;
import cn.com.darly.videoandroidpm.common.StaticListener;
import cn.com.darly.videoandroidpm.common.SystemLoginInfo;
import cn.com.darly.videoandroidpm.common.VpmTimer;
import cn.com.darly.videoandroidpm.common.dao.ConversationMessageInfo;
import cn.com.darly.videoandroidpm.ui.PMActivity;
import cn.com.darly.videoandroidpm.ui.conversation.chat.ConversationActivity;
import cn.com.darly.videoandroidpm.ui.conversation.video.VideoAcceptActivity;
import cn.com.darly.videoandroidpm.ui.registerfriend.AddFriendActivity;

/**
 * 连接MQTT消息服务器功能服务
 * @author Darly/张宇辉/2018/4/26 13:55
 * @version 1.0/cn.com.darly.videoandroidpm.ui.service
 */
public class MqttServiceImplementer extends Service{

    private static MqttAndroidClient client;
    private MqttConnectOptions conOpt;

    private String host = "tcp://193.169.100.110:61613";
    private String userName = "admin";
    private String passWord = "password";
    private static String myTopic = "vpm@" + BaseApplication.getInstance().getDevId();
    private String clientId = BaseApplication.getInstance().getDevId();

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            String message= (String)msg.obj;
            String [] msges = message.split("#");
            if ("200".equals(msges[0])) {
                //用户进行视频呼叫。并且好友接到视频呼叫请求。
                LoginInfo friednInfo = new Gson().fromJson(msges[1], new TypeToken<LoginInfo>() {
                }.getType());
                Intent intent = new Intent(BaseApplication.getInstance(), VideoAcceptActivity.class);//将要跳转的界面 //
                intent.putExtra("LoginInfo", friednInfo);
                intent.putExtra("RTMP",msges[2]);
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }else if ("201".equals(msges[0])){
                //对方取消视频通话
                StaticListener.callConsoled(msges[0]);
            }else if ("400".equals(msges[0])){
                //对方接受视频通话
                StaticListener.connectVideo(msges[0],msges[2]);
            }else if ("401".equals(msges[0])){
                //对方拒绝视频通话
                StaticListener.connectVideo(msges[0],null);
            }else {
                showNotifictionIcon(BaseApplication.getInstance(), msges);
            }
        }
    };


    public void showNotifictionIcon(Context context,String[] msges) {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        // Intent intent = new Intent();//只显示通知，无页面跳转
        builder.setAutoCancel(true);//点击后消失
        builder.setSmallIcon(R.mipmap.ic_launcher);//设置通知栏消息标题的头像
        builder.setDefaults(NotificationCompat.DEFAULT_SOUND);//设置通知铃声
        builder.setTicker("消息");
        builder.setContentTitle("漫多");
        Intent intent = null;
        switch (Integer.parseInt(msges[0])) {
            case 1:
                //对方申请好友通知
                builder.setContentText(msges[1]); //利用PendingIntent来包装我们的intent对象,使其延迟跳转
                intent = new Intent(context, AddFriendActivity.class);//将要跳转的界面 //
                break;
            case 2:
                //用户同意好友通知
                builder.setContentText(msges[1]); //利用PendingIntent来包装我们的intent对象,使其延迟跳转
                intent = new Intent(context, PMActivity.class);//将要跳转的界面 //
                break;
            case 3:
                break;
            case 4:
                break;
            case 10:
                //消息推送。聊天信息。以JSON形式过来
                intent = new Intent(context, ConversationActivity.class);//将要跳转的界面 //
                intent.putExtra("from",msges[2] ==null? "":msges[2]);
                intent.putExtra("name",msges[3] ==null? "":msges[3]);
                intent.putExtra("icon",msges[4] ==null? "":msges[4]);
                MessageInfo info = new Gson().fromJson(msges[1], new TypeToken<MessageInfo>() {
                }.getType());
                //用户消息推送过来后，消息在这里进行保存。
                if (SystemLoginInfo.getboolean(SystemLoginInfo.LOGIN) && info != null) {
                    //登录保存。
                    ConversationMessageInfo savedInfo = new ConversationMessageInfo();
                    savedInfo.setMsgId(info.getId());
                    savedInfo.setMsgFrom(info.getMsgFrom());
                    savedInfo.setMsgTo(info.getMsgTo());
                    savedInfo.setMsgType("0");
                    savedInfo.setMsgTime(info.getMsgTime());
                    savedInfo.setMsgContent(info.getMsgContent());
                    savedInfo.setMsgOther(info.getMsgOther());
                    savedInfo.setMsgSend(true);
                    savedInfo.save();
                    if("cn.com.darly.videoandroidpm.ui.conversation.chat.ConversationActivity".equals(getRunningActivityName())){
                        //使用静态接口，刷新页面。
                        boolean isshou  = StaticListener.messageChange(savedInfo);
                        if (isshou) {
                            return;
                        }
                    }else{
                        //start DeviceControlActivity
                        intent.putExtra("ConversationMessageInfo", savedInfo);
                        builder.setContentText(savedInfo.getMsgContent()); //利用PendingIntent来包装我们的intent对象,使其延迟跳转
                    }
                }

                break;
            default:
                //0为测试信息组
                builder.setContentText(msges[1]); //利用PendingIntent来包装我们的intent对象,使其延迟跳转
                intent = new Intent(context, PMActivity.class);//将要跳转的界面 //
                break;
        }


        PendingIntent intentPend = PendingIntent.getActivity(context, new Random().nextInt(), intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(intentPend);
        NotificationManager manager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
        manager.notify(new Random().nextInt(), builder.build());

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        init();
        return super.onStartCommand(intent, flags, startId);
    }
    private void init() {
        // 服务器地址（协议+地址+端口号）
        String uri = host;
        client = new MqttAndroidClient(this, uri, clientId);
        // 设置MQTT监听并且接受消息
        client.setCallback(mqttCallback);
        conOpt = new MqttConnectOptions();
        // 是否去哪个缓存
        conOpt.setCleanSession(true);
        // 设置超时时间，单位：秒
        conOpt.setConnectionTimeout(10);
        // 心跳包发送间隔，单位：秒
        conOpt.setKeepAliveInterval(20);
        // 用户名
        conOpt.setUserName(userName);
        // 密码
        conOpt.setPassword(passWord.toCharArray());

        // last will message
        boolean doConnect = true;
        String message = "{\"terminal_uid\":\"" + clientId + "\"}";
        String topic = myTopic;
        Integer qos = 0;
        Boolean retained = false;
        if ((!message.equals("")) || (!topic.equals(""))) {
            // 最后的遗嘱
            try {
                conOpt.setWill(topic, message.getBytes(), qos.intValue(), retained.booleanValue());
            } catch (Exception e) {
                DLog.i("Exception Occured");
                doConnect = false;
                iMqttActionListener.onFailure(null, e);
            }
        }

        if (doConnect) {
            doClientConnection();
        }

    }

    /** 连接MQTT服务器 */
    private void doClientConnection() {
        if (!client.isConnected() && isConnectIsNomarl()) {
            try {
                client.connect(conOpt, null, iMqttActionListener);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }
    }

    /** 判断网络是否连接 */
    private boolean isConnectIsNomarl() {
        ConnectivityManager connectivityManager = (ConnectivityManager) this.getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo info = connectivityManager.getActiveNetworkInfo();
        if (info != null && info.isAvailable()) {
            String name = info.getTypeName();
            DLog.i( "当前网络名称：" + name);
            return true;
        } else {
            DLog.i( "没有可用网络");
            return false;
        }
    }

    // MQTT是否连接成功
    private IMqttActionListener iMqttActionListener = new IMqttActionListener() {

        @Override
        public void onSuccess(IMqttToken arg0) {
            DLog.i( "连接成功 ");
            try {
                // 订阅myTopic话题
                client.subscribe(myTopic,1);
            } catch (MqttException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(IMqttToken arg0, Throwable arg1) {
            arg1.printStackTrace();
            // 连接失败，重连
        }
    };

    // MQTT监听并且接受消息
    private MqttCallback mqttCallback = new MqttCallback() {

        @Override
        public void messageArrived(String topic, MqttMessage message) throws Exception {
            Message msg = new Message();
            msg.obj = new String(message.getPayload());
            handler.sendMessage(msg);
            DLog.i( "messageArrived:" + new String(message.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken arg0) {
        }

        @Override
        public void connectionLost(Throwable arg0) {
            // 失去连接，重连
        }
    };



    public static void publish(String msg){
        String topic = myTopic;
        Integer qos = 0;
        Boolean retained = false;
        try {
            client.publish(topic, msg.getBytes(), qos.intValue(), retained.booleanValue());
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }


    /**
     * 根据栈内页面，获取展示的Activity页面
     * @return
     */
    private String getRunningActivityName(){
        ActivityManager activityManager=(ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list=activityManager.getRunningTasks(1);
        ActivityManager.RunningTaskInfo info=list.get(0);
        ComponentName componentName=info.topActivity;
        return componentName.getClassName();
    }


    @Override
    public void onDestroy() {
        try {
            client.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
        super.onDestroy();
    }
}
